package com.david.mydemo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
public class OssFileUtil {

    public static String uploadFile(MultipartFile file, String endpoint, String bucketName, OSS ossClient) {
        String fileName = file.getOriginalFilename();
        if (fileName.contains(".")) {
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        } else {
            fileName += System.currentTimeMillis();
        }
        try {
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            // 返回文件的URL
//            return "https://" + bucketName + "." + endpoint + "/" + fileName;
            return fileName;
        } catch (Exception e) {
            log.error("上传附件报错，错误信息：", e);
            return null;
        }
    }

    public static void deleteFile(String fileName, String bucketName, OSS ossClient) {
        try {
            ossClient.deleteObject(bucketName, fileName);
        } catch (Exception e) {
            log.error("删除附件报错，错误信息：", e);
        }
    }

    /**
     * 审核上传的图片
     *
     * @param url
     * @return
     */
    public static String checkOssUploadFile(IAcsClient acsClient, String url, String bucketName, String fileName, OSS ossClient) {
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        //指定API返回格式
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
        //指定请求方法
        imageSyncScanRequest.setMethod(MethodType.POST);
        imageSyncScanRequest.setEncoding("utf-8");
        //支持http 和 https
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
        JSONObject httpBody = new JSONObject();
        /**
         * 设置要检测的风险场景
         * porn : 鉴黄
         * terrorism : 暴恐
         * ad : 广告
         * live : 不良场景
         * qrcode : 二维码
         * logo : 商标
         * 图片审核是分场景收费的
         */
//        httpBody.put("scenes", Arrays.asList("porn", "terrorism", "ad", "live", "qrcode", "logo"));
        httpBody.put("scenes", Arrays.asList("porn", "terrorism", "live"));
        /**
         * 设置待检测图片 , 一张图片对应一个task
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());
        //设置图片链接为上传后的URL. URL中有特殊自读,需要对URL进行encode编码
        task.put("url", url);
        task.put("time", new Date());
        httpBody.put("tasks", Collections.singletonList(task));
        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()), "UTF-8", FormatType.JSON);
        //设置超时时间
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = acsClient.doAction(imageSyncScanRequest);
        } catch (Exception e) {
            log.error("图片审核失败，错误信息：", e);
        }
        //服务端接收请求 , 完成处理后返回的结果
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            int requestCode = scrResponse.getIntValue("code");
            //每一张图片的检测结果
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    //单张图片的处理结果
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    //图片对应检测场景的处理结果. 如果是多个场景 , 则会有每一个场景的检测结果
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        for (Object sceneResult : sceneResults) {
                            log.info("图片开始审核");
                            String scene = ((JSONObject) sceneResult).getString("scene");
                            String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                            //根据 scene 和 suggestion 做相关处理
                            log.info("响应结果参数： scene = {}, suggestion = {}", scene, suggestion);
                            if ("review".equals(suggestion) || "block".equals(suggestion)) {
                                log.info("图片审核不通过");
                                //只要不是"pass" , 直接拒绝 , 删除图片
                                deleteFile(fileName, bucketName, ossClient);
                                return "block";
                            }
                            log.info("图片审核成功");
                            return "pass";
                        }
                    } else {
                        // 单张图片处理失败，原因视具体的情况详细分析。
                        log.error("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                // 表明请求整体处理失败，原因视具体的情况详细分析。
                log.error("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
        log.error("checkImageisFail");
        return "error";
    }

    /**
     * 审核文本内容
     *
     * @param acsClient
     * @param region
     * @param text
     * @return
     * @throws UnsupportedEncodingException
     */
    public static List<Map<String, String>> checkText(IAcsClient acsClient, String region, String text) throws UnsupportedEncodingException {
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(MethodType.POST); // 指定请求方法。
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId(region);
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符。
         */
        task1.put("content", text);

        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景。文本垃圾检测请传递antispam。
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        System.out.println(JSON.toJSONString(data, true));
        log.info("文本检测参数：{}", JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间。
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = acsClient.doAction(textScanRequest);
            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                log.info("scrResponse响应数据：{}", JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    List<Map<String, String>> resultMaps = new ArrayList<>();
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // 根据scene和suggetion做相关处理。
                                // suggestion为pass表示未命中垃圾。suggestion为block表示命中了垃圾，可以通过label字段查看命中的垃圾分类。
                                log.info("响应结果参数： scene = {}, suggestion = {}", scene, suggestion);

                                Map<String, String> resultMap = new HashMap<>();
                                resultMap.put("scene", scene);
                                resultMap.put("suggestion", suggestion);
                                resultMaps.add(resultMap);
                            }
                        } else {
                            log.error("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                        }
                    }
                    return resultMaps;
                } else {
                    log.error("detect not success. code:" + scrResponse.getInteger("code"));
                }
            } else {
                log.error("response not success. status:" + httpResponse.getStatus());
            }
        } catch (Exception e) {
            log.error("checkText is error", e);
        }
        return null;
    }

    public static void main(String[] args) {
//        String url = "https://dispatch-pioneer.oss-cn-hangzhou.aliyuncs.com/中国移动.png";
//        String accessKey = "LTAI5tLU9A3xfGpsC2T8VgoS";
//        String secretKey = "W2SUnl3zukiCOrCiWjelmzUiOBi6vR";
//        String bucketName = "dispatch-pioneer";
//        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//        String region = "cn-hangzhou";
//        String product = "Green";
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
//        DefaultProfile profile = DefaultProfile.getProfile(region, accessKey, secretKey);
//        DefaultProfile.addEndpoint(region, product, endpoint); //地区要和图片存储的地区一致
//        IAcsClient acsClient = new DefaultAcsClient(profile);
//        String fileName = "中国移动.png";
//        String s = checkOssUploadFile(acsClient, url, bucketName, fileName, ossClient);
//        System.out.println(s);

        System.out.println(System.currentTimeMillis());

        String fileName = "abc.jpg";
        System.out.println(fileName.indexOf("."));
        System.out.println(fileName.lastIndexOf("."));
        System.out.println(fileName.substring(0, fileName.lastIndexOf(".")));
        System.out.println(fileName.substring(fileName.lastIndexOf(".")));
        fileName = fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
//        String aa = fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
//        String aa = a.split("\\.")[0] + System.currentTimeMillis() + "." + a.split("\\.")[1];
        System.out.println(fileName);

    }

}
